from .models import User,Order,State
from .serializers import OrderSerializer, UserSerializer, StateSerializer
from rest_framework import viewsets
from . import permissions


class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = [permissions.IsAdminUser]

class StateViewSet(viewsets.ModelViewSet):
    queryset = State.objects.all()
    serializer_class = StateSerializer
    permission_classes = [permissions.IsAuthenticated, permissions.IsLabMemberOrReadOnly]

class OrderViewSet(viewsets.ModelViewSet):
    queryset = Order.objects.all()
    serializer_class = OrderSerializer
    permission_classes = [permissions.IsAuthenticated , permissions.IsOwnerOrAdmin]

    def get_queryset(self):
        if self.request.user.is_superuser or permissions.is_from_lab_group(self.request.user):
            return  Order.objects.all()
        elif not self.request.user.is_staff:
            return Order.objects.filter(seller=self.request.user)
        else:
            groups = self.request.user.groups.all()
            result = Order.objects.none()
            for group in groups:
                users= group.user_set.all()
                result |= Order.objects.filter(seller__in=users)
            return result
